//
//  MBConversationViewController.m
//  Meboo
//
//  Created by kyo on 2023/10/18.
//

#import "MBConversationViewController.h"
#import "MBConversitionNavView.h"
#import "ChatSelectImageViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "MBChatPreviewVideoViewController.h"
#import "MBChatDataManager.h"
#import "MBThumbnailCache.h"
#import "IQKeyboardManager.h"
#import "KLVipViewController.h"
#import "NSPhotoViewController.h"
@interface MBConversationViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource,
RCIMReceiveMessageDelegate,
UIImagePickerControllerDelegate
>
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) MBConversitionNavView *conversitionNavView;
@property (nonatomic, strong) UILabel *placeLab;
@property (nonatomic, strong) UIButton *imageSelectBtn;
@property (nonatomic, strong) UIButton *emojiSelectBtn;

@property (nonatomic, strong) UIButton *sendMessageBtn;
//
@property (nonatomic, strong) MBChatDataManager *chatDataManager;
@property (nonatomic, strong) UIView *secView;
//已成功发送的次数
@property (nonatomic, assign) NSInteger sendedNum;
//是否发过信息
@property (nonatomic, assign) BOOL isSended;
@end

@implementation MBConversationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HEXS(@"22253C");
    [self setupUI];
    [IQKeyboardManager sharedManager].enable = NO;
    [RCIM sharedRCIM].receiveMessageDelegate = self;
    [self setNavTitle];
    //非会员,调用
    if (self.isFromList && ![MBUserAccount defaultAccount].isVip) {
        [self getUserMessageNum];
    }
    
    //截屏事件监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(screenshots) name:UIApplicationUserDidTakeScreenshotNotification  object:nil];
    //录屏事件监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(screenrecording) name:UIScreenCapturedDidChangeNotification  object:nil];
    if (self.isFlashChat) {
        [self sendFlashChat];
    }
    
    [self getRCUserInfo];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.chatSessionInputBarControl.inputTextView.text = nil;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //安卓端发来的视频没有缩略图,在此处加载缩略图并缓存和刷新
    for (int i = 0; i<self.conversationDataRepository.count; i++) {
        RCMessageModel *model = [self.conversationDataRepository objectAtIndex:i];
        if ([model.objectName isEqualToString:@"RC:SightMsg"] && model.messageDirection == MessageDirection_RECEIVE) {
            RCSightMessage *message = (RCSightMessage*)model.content;
            if (message.thumbnailImage == nil) {
                UIImage *image = [[MBThumbnailCache sharedCache] getThumbnailImageForKey:message.remoteUrl];
                if (image == nil) {
                    image = [self getThumbnailImage:message.remoteUrl];
                    [[MBThumbnailCache sharedCache] setThumbnailImage:image forKey:message.remoteUrl];
                    [self.conversationMessageCollectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:i inSection:0]]];
                }
            }
        }
    }
}

- (void)getRCUserInfo {
    __WeakSelf
    dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        [weakSelf.chatDataManager getUserInfoWithUserId:self.targetId completion:^(RCUserInfo * _Nonnull userInfo) {
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:self.targetId];
            dispatch_group_leave(group);
        }];
    });
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        [weakSelf.chatDataManager getUserInfoWithUserId:[MBUserAccount defaultAccount].chatUserId completion:^(RCUserInfo * _Nonnull userInfo) {
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:[MBUserAccount defaultAccount].chatUserId];
            dispatch_group_leave(group);
        }];
    });
    
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.conversationMessageCollectionView reloadData];
        });
    });
    
    //自己的信息也加载一遍  无需进组,因为不参与本页面刷新 在下个页面会用到
    RCUserInfo *meInfo = [[RCIM sharedRCIM] getUserInfoCache:[MBUserAccount defaultAccount].chatUserId];
    if (meInfo.portraitUri.length == 0) {
        [weakSelf.chatDataManager getUserInfoWithUserId:[MBUserAccount defaultAccount].chatUserId completion:^(RCUserInfo * _Nonnull userInfo) {
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:[MBUserAccount defaultAccount].chatUserId];
        }];
    }
}

//#pragma mark - 设置状态栏颜色
//- (UIStatusBarStyle)preferredStatusBarStyle {
//    return UIStatusBarStyleLightContent;
//}

- (void)setIsSayHi:(BOOL)isSayHi {
    _isSayHi = isSayHi;
}

- (void)setIsFlashChat:(BOOL)isFlashChat{
    _isFlashChat = isFlashChat;
}

- (void)setIsFromWLM:(BOOL)isFromWLM {
    _isFromWLM = isFromWLM;
}

//重写pop返回事件,用以确定block的调用
- (void)didMoveToParentViewController:(UIViewController *)parent {
    [super didMoveToParentViewController:parent];
    if (self.sendedNum > 0 && self.sendMessageBlock && ![MBUserAccount defaultAccount].isVip) {
        self.sendMessageBlock(self.sendedNum);
    }
    
    if (self.isFromWLM && self.isSended) {
        [MBNotificationCenter postNotificationName:WLM_CHAT_SENDED object:nil];
    }
}

#pragma mark - Private Method
- (void)screenshots {
    [MBProgressHUD showWarnMessage:@"No screenshot allowed."];
}

- (void)screenrecording {
    if ([UIScreen mainScreen].isCaptured) {
        [MBProgressHUD showWarnMessage:@"No screen recording allowed."];
    }
}


- (void)getUserMessageNum {
    [self.chatDataManager getUserMessageNumWithUserCode:self.targetId type:1 success:^(BOOL success) {
    }];
}

- (void)setNavTitle {
    RCUserInfo *userInfo = [[RCIM sharedRCIM] getUserInfoCache:self.targetId];
    if (userInfo.name.length > 0) {
        self.conversitionNavView.nameStr = userInfo.name;
        if ([self.conversitionNavView.nameStr isEqualToString:@"user<>"]) {
            self.conversitionNavView.nameStr = @"Meboo";
        }
    } else {
        [self.chatDataManager getUserInfoWithUserId:self.targetId completion:^(RCUserInfo * _Nonnull userInfo) {
            self.conversitionNavView.nameStr = userInfo.name;
            if ([self.conversitionNavView.nameStr isEqualToString:@"user<>"]) {
                self.conversitionNavView.nameStr = @"Meboo";
            }
            [[RCIM sharedRCIM] refreshUserInfoCache:userInfo withUserId:self.targetId];
        }];
    }
}

#pragma mark - Public Method

- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    if ([message.targetId isEqualToString:self.targetId]) {
        RCMessageModel *model = [RCMessageModel modelWithMessage:message];
        [self.conversationDataRepository addObject:model];
        __WeakSelf
        if (left == 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.conversationMessageCollectionView reloadData];
                [weakSelf scrollToBottomAnimated:YES];
            });
        }
    }
}

- (BOOL)onRCIMCustomLocalNotification:(RCMessage *)message withSenderName:(NSString *)senderName {
    NSLog(@"");
    return NO;
}

- (BOOL)onRCIMCustomAlertSound:(RCMessage *)message {
    NSLog(@"");
    return NO;
}

#pragma mark - Action

- (void)sendMessageAction {
    if ([self.targetId isEqualToString:@"1000000000000000000"]) {
        //
    } else {
        //首先判断是否会员
        //非会员判断 免费次数
        if ([MBUserAccount defaultAccount].isVip) {
            
        } else {
            if (self.sendedNum >= self.chatDataManager.messagesNumber) {
                //非会员,免费用完了,跳转VIP
                [self.navigationController pushViewController:[KLVipViewController new] animated:YES];
                return;
            }
        }
    }
    
    if (self.chatSessionInputBarControl.inputTextView.text.length == 0) {
        return;
    }
    __WeakSelf
    RCTextMessage *messageContent = [RCTextMessage messageWithContent:self.chatSessionInputBarControl.inputTextView.text];
    
    RCMessage *message = [[RCMessage alloc]
                          initWithType:ConversationType_PRIVATE
                          targetId:self.targetId
                          direction:MessageDirection_SEND
                          content:messageContent];
    
    
    [[RCIM sharedRCIM]
     sendMessage:message
     pushContent:nil
     pushData:nil
     successBlock:^(RCMessage *successMessage) {
        weakSelf.isSended = YES;
        //成功
        weakSelf.sendedNum++;
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.chatSessionInputBarControl.inputTextView.text = nil;
        });
    }
     errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) {
        //失败
    }];
    
}

- (void)sendFlashChat {
    __WeakSelf
    RCTextMessage *messageContent = [RCTextMessage messageWithContent:@"Hi there! Let's make this app less boring together"];
    
    RCMessage *message = [[RCMessage alloc]
                          initWithType:ConversationType_PRIVATE
                          targetId:self.targetId
                          direction:MessageDirection_SEND
                          content:messageContent];
    
    
    [[RCIM sharedRCIM]
     sendMessage:message
     pushContent:nil
     pushData:nil
     successBlock:^(RCMessage *successMessage) {
        //成功
        weakSelf.sendedNum++;
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.chatSessionInputBarControl.inputTextView.text = nil;
        });
    }
     errorBlock:^(RCErrorCode nErrorCode, RCMessage *errorMessage) {
        //失败
    }];
}

- (void)imageSelectAction {
    [self uploadImg];
//    NSPhotoViewController *photoViewController = [NSPhotoViewController new];
//    photoViewController.targetId = self.targetId;
//    [self.navigationController pushViewController:photoViewController animated:YES];
}
//cell1.pictureView.contentMode = UIViewContentModeScaleAspectFill;
#pragma mark -- collectionView  delegate datasource
- (void)willDisplayMessageCell:(RCMessageBaseCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    
    RCMessageModel *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
    BOOL isPrivate = [model.expansionDic[@"isPrivate"] boolValue];
    if ([cell isKindOfClass:[RCTextMessageCell class]] && model.conversationType == ConversationType_PRIVATE) {
        if (model.content && (model.sentStatus == SentStatus_READ ||model.sentStatus == SentStatus_SENT) && model.messageDirection == MessageDirection_SEND) {
            for (UIView *view in [((RCMessageCell *)cell).statusContentView subviews]) {
                [view removeFromSuperview];
            }
        }else{
            UIView *tagView = [((RCMessageCell *)cell).statusContentView viewWithTag:1001];
            if (tagView) {
                [tagView removeFromSuperview];
            }
        }
    }
    //&& model.messageDirection == MessageDirection_RECEIVE
    if ([model.objectName isEqualToString:@"RC:ImgMsg"]) {
        RCImageMessage *message = (RCImageMessage*)model.content;
        RCImageMessageCell *cell1 = (RCImageMessageCell *)cell;
        for (UIView *view in cell1.pictureView.subviews) {
            if ([view isKindOfClass:[UIVisualEffectView class]]) {
                [cell1.pictureView.subviews.lastObject removeFromSuperview];
                [view removeFromSuperview];
            }
        }
        
        //2，iOS 系统自带的高斯模糊效果
        UIBlurEffect *blurEffrct =[UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemUltraThinMaterialDark];
        UIVisualEffectView *effectView = [[UIVisualEffectView alloc]initWithEffect:blurEffrct];
//        effectView.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:0 / 255.0 blue:0 / 255.0 alpha:0.6];
        
            effectView.alpha = 0.95;
        effectView.frame = cell1.pictureView.bounds;

        
//        if (isPrivate && ![MBUserAccount defaultAccount].isVip) {
        if (isPrivate) {
            [cell1.pictureView addSubview:effectView];
            
            UIImageView *secretImageView = [UIImageView new];
            secretImageView.image = ImageWithName(@"chat_image_recive_secret");
            [cell1.pictureView  addSubview:secretImageView];
            [secretImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(cell1.pictureView);
            }];
        }
        
        if (message.thumbnailImage == nil) {
            cell1.nicknameLabel.hidden = YES;
            [cell1.pictureView sd_setImageWithURL:[NSURL URLWithString:message.imageUrl]];
            cell1.pictureView.contentMode = UIViewContentModeScaleAspectFill;
            cell1.messageTimeLabel.text = [self cStringFromTimestamp:model.sentTime];
            cell1.pictureView.frame = CGRectMake(cell1.pictureView.frame.origin.x, cell1.pictureView.frame.origin.y, MBWidthScale(80), MBHeightScale(120));
            
            cell1.messageContentView.frame = CGRectMake(cell1.messageContentView.frame.origin.x, cell1.messageContentView.frame.origin.y, MBWidthScale(80), MBHeightScale(120));
            effectView.frame = cell1.pictureView.bounds;
            
            UIBezierPath *maskPath;
                cell1.messageContentView.backgroundColor = UIColor.clearColor;
                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell1.messageContentView.bounds byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(MBHeightScale(12),MBHeightScale(12))];//圆角大小
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = cell1.messageContentView.bounds;
            maskLayer.path = maskPath.CGPath;
            cell1.messageContentView.layer.mask = maskLayer;
            return;
        } else {
            NSLog(@"");
        }
    }
    // && model.messageDirection == MessageDirection_RECEIVE
    else if ([model.objectName isEqualToString:@"RC:SightMsg"]) {
        RCSightMessage *message = (RCSightMessage*)model.content;
        RCMessageCell *cell1 = (RCMessageCell *)cell;
        
        for (UIView *view in cell1.messageContentView.subviews) {
            if ([view isKindOfClass:[UIVisualEffectView class]]) {
                [cell1.messageContentView.subviews.lastObject removeFromSuperview];
                [view removeFromSuperview];
            }
            
            if (view.tag >= 1000) {
                [view removeFromSuperview];
            }
        }
        
        //2，iOS 系统自带的高斯模糊效果
        UIBlurEffect *blurEffrct =[UIBlurEffect effectWithStyle:UIBlurEffectStyleSystemUltraThinMaterialDark];
        UIVisualEffectView *effectView = [[UIVisualEffectView alloc]initWithEffect:blurEffrct];
//        effectView.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:0 / 255.0 blue:0 / 255.0 alpha:0.6];
        
            effectView.alpha = 0.95;
        effectView.frame = cell1.messageContentView.bounds;
        
        UIImageView *secretImageView = [UIImageView new];
        secretImageView.image = ImageWithName(@"chat_image_recive_secret");
        
        if (isPrivate) {
//        if (isPrivate && ![MBUserAccount defaultAccount].isVip) {
            [cell1.messageContentView addSubview:effectView];
            
            [cell1.messageContentView  addSubview:secretImageView];
            [secretImageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(cell1.messageContentView);
            }];
        }
        
        if (message.thumbnailImage == nil) {
            RCMessageCell *cell1 = (RCMessageCell *)cell;
            cell1.nicknameLabel.hidden = YES;
            cell1.messageTimeLabel.text = [self cStringFromTimestamp:model.sentTime];
            
            UIImageView *thumbnailImage = [UIImageView new];
            thumbnailImage.tag = 1000;
            thumbnailImage.image = [[MBThumbnailCache sharedCache] getThumbnailImageForKey:message.remoteUrl];
            UIImageView *playImage = [UIImageView new];
            playImage.tag = 1001;
            playImage.image = ImageWithName(@"chat_sight_message_icon");
            
            cell1.messageContentView.frame = CGRectMake(cell1.messageContentView.frame.origin.x, cell1.messageContentView.frame.origin.y, MBWidthScale(80), MBHeightScale(120));
            [cell1.messageContentView addSubview:thumbnailImage];
            [thumbnailImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(cell1.messageContentView);
            }];
            
            [cell1.messageContentView addSubview:playImage];
            [playImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(cell1.messageContentView);
                make.width.height.mas_equalTo(41);
            }];
            
            effectView.frame = cell1.messageContentView.bounds;
            [cell1.messageContentView bringSubviewToFront:effectView];
            [cell1.messageContentView bringSubviewToFront:secretImageView];
            
            UIBezierPath *maskPath;
                cell1.messageContentView.backgroundColor = UIColor.clearColor;
                maskPath = [UIBezierPath bezierPathWithRoundedRect:cell1.messageContentView.bounds byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(MBHeightScale(12),MBHeightScale(12))];//圆角大小
            CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
            maskLayer.frame = cell1.messageContentView.bounds;
            maskLayer.path = maskPath.CGPath;
            cell1.messageContentView.layer.mask = maskLayer;
            return;
        }
    }
    
    if ([model.objectName isEqualToString:@"RC:TxtMsg"]) {
        RCMessageCell *cell1 = (RCMessageCell *)cell;
        UIImageView *backImageView = cell1.messageContentView.subviews[0];
        RCAttributedLabel *backLab = cell1.messageContentView.subviews[2];
//        backLab.font = PDRegularScale(15);
        backLab.font = [UIFont fontWithName:@"PlayfairDisplay-Regular" size:15];
        if (cell1.messageDirection == MessageDirection_SEND) {
            backLab.textColor = HEXS(@"ffffff");
        } else {
            backLab.textColor = HEXS(@"000000");
        }
        backImageView.hidden = YES;
    }
    
    RCMessageCell *cell1 = (RCMessageCell *)cell;
    cell1.messageTimeLabel.text = [self cStringFromTimestamp:model.sentTime];
    cell1.nicknameLabel.hidden = YES;
    cell1.contentView.backgroundColor = UIColor.clearColor;
    UIBezierPath *maskPath;
    if (cell1.messageDirection == MessageDirection_SEND) {
        cell1.messageContentView.backgroundColor = HEXS(@"B92176");
        maskPath = [UIBezierPath bezierPathWithRoundedRect:cell1.messageContentView.bounds byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(MBHeightScale(12),MBHeightScale(12))];//圆角大小
    } else {
        cell1.messageContentView.backgroundColor = UIColor.whiteColor;
        maskPath = [UIBezierPath bezierPathWithRoundedRect:cell1.messageContentView.bounds byRoundingCorners:(UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight) cornerRadii:CGSizeMake(MBHeightScale(12),MBHeightScale(12))];//圆角大小
    }
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = cell1.messageContentView.bounds;
    maskLayer.path = maskPath.CGPath;
    cell1.messageContentView.layer.mask = maskLayer;
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    RCMessageModel *model = [self.conversationDataRepository objectAtIndex:indexPath.row];
    if ([model.objectName isEqualToString:@"RC:ImgMsg"] && model.messageDirection == MessageDirection_RECEIVE) {
        RCImageMessage *message = (RCImageMessage*)model.content;
        if (message.thumbnailImage == nil) {
            return CGSizeMake(ScreenWidth, MBHeightScale(180));
        }
    }
    if ([model.objectName isEqualToString:@"RC:SightMsg"] && model.messageDirection == MessageDirection_RECEIVE) {
        RCSightMessage *message = (RCSightMessage*)model.content;
        if (message.thumbnailImage == nil) {
            return CGSizeMake(ScreenWidth, MBHeightScale(180));
        }
    }
    return [super collectionView:collectionView layout:collectionViewLayout sizeForItemAtIndexPath:indexPath];
    
}

//获取视频的缩略图(第一帧)
- (UIImage *)getThumbnailImage:(NSString *)videoUrl {
    UIImage *theImage = nil;
     AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:videoUrl] options:nil];
     AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
     generator.appliesPreferredTrackTransform = YES;
     NSError *err = NULL;
     CMTime time = CMTimeMake(1, 60);
     CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&err];

     theImage = [[UIImage alloc] initWithCGImage:imgRef];
     CGImageRelease(imgRef);
     return theImage;
}


// 时间戳—>字符串时间
- (NSString *)cStringFromTimestamp:(long long)timestamp {
    timestamp = timestamp/1000;
    //时间戳转时间的方法
    NSDate *timeData = [NSDate dateWithTimeIntervalSince1970:timestamp];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm"];
    NSString *strTime = [dateFormatter stringFromDate:timeData];
    NSCalendar *calendar = [NSCalendar currentCalendar];//定义一个NSCalendar对象
    
    if ([calendar isDateInToday:timeData]) {
        //是否是今天
        return strTime;
    } else if ([calendar isDateInYesterday:timeData]) {
        //是否是昨天
        return @"Yesterday";
    } else {
        [dateFormatter setDateFormat:@"MM/dd"];
        return [dateFormatter stringFromDate:timeData];
    }
}

/// 输入框中内容发生变化的回调
- (void)inputTextViewDidChange:(UITextView *)inputTextView {
    NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
    if ([[inputTextView.text stringByTrimmingCharactersInSet:set] length] == 0) {
        // 字符串全是空格
        self.sendMessageBtn.enabled = NO;
    } else {
        // 字符串不全是空格
        self.sendMessageBtn.enabled = YES;
    }
}

- (void)emojiView:(RCEmojiBoardView *)emojiView didTouchedEmoji:(NSString *)touchedEmoji {
    NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
    if ([[self.chatSessionInputBarControl.inputTextView.text stringByTrimmingCharactersInSet:set] length] == 0) {
        // 字符串全是空格
        self.sendMessageBtn.enabled = NO;
    } else {
        // 字符串不全是空格
        self.sendMessageBtn.enabled = YES;
    }
}

//文本内容点击键盘上的发送
- (void)inputTextViewDidTouchSendKey:(UITextView *)inputTextView {
    [self sendMessageAction];
}

//emoji点击键盘上的发送
- (void)emojiView:(RCEmojiBoardView *)emojiView didTouchSendButton:(UIButton *)sendButton {
    [self sendMessageAction];
}


- (void)uploadImg{
    __WeakSelf
    //获取
    UIAlertController  *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if ([self getIsIpad]){
        alert.popoverPresentationController.sourceView = self.view;
        alert.popoverPresentationController.sourceRect = CGRectMake(ScreenWidth/2,ScreenHeight/2,0,0);
        alert.popoverPresentationController.permittedArrowDirections = 0;
    }
    
    UIAlertAction  *cameraAction = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];//读取设备授权状态
        if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
//            [SVProgressHUD showInfoWithStatus:RVString(@"CameraPermissions")];
        }else{
            //打开照相机
            if ([UIImagePickerController  isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController  *picker = [[UIImagePickerController alloc]init];
                picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie, nil];
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                picker.delegate = self;
                picker.allowsEditing = NO;
                [self.currentViewController presentViewController:picker animated:YES completion:^{}];
            }
        }
    }];
    
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"Albums" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //从相册中获取图片
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = weakSelf;
        picker.allowsEditing = NO;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeImage, (NSString *)kUTTypeMovie, nil];
        [self.currentViewController presentViewController:picker animated:YES completion:^{}];
    }];
    
    UIAlertAction  *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:photoAction];
    [alert  addAction:cameraAction];
    [alert addAction:cancelAction];
    [self.currentViewController presentViewController:alert animated:YES completion:nil];
}

//如果想要判断设备是ipad，要用如下方法
- (BOOL)getIsIpad {
    NSString *deviceType = [UIDevice currentDevice].model;
    
    if([deviceType isEqualToString:@"iPhone"]) {
        //iPhone
        return NO;
    }
    else if([deviceType isEqualToString:@"iPod touch"]) {
        //iPod Touch
        return NO;
    }
    else if([deviceType isEqualToString:@"iPad"]) {
        //iPad
        return YES;
    }
    return NO;
}


#pragma mark - UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    __WeakSelf
    ChatSelectImageViewController *headVC = [[ChatSelectImageViewController alloc]init];
    headVC.targetId = self.targetId;
    UIImage *editedImage = info[UIImagePickerControllerOriginalImage];
    if (editedImage) {
        //图片
        headVC.oldImage = editedImage;
    } else {
        //视频
        headVC.videoUrl = info[UIImagePickerControllerMediaURL];
    }
    [weakSelf.currentViewController.navigationController pushViewController:headVC animated:YES];
}

#pragma mark -- delegate 消息处理的回调
//点击消息 Cell 中的 URL
- (void)didTapUrlInMessageCell:(NSString *)url model:(RCMessageModel *)model{
    NSLog(@"");
}

//点击消息 Cell 中的电话号码
- (void)didTapPhoneNumberInMessageCell:(NSString *)phoneNumber model:(RCMessageModel *)model{
    
}

- (void)didLongTouchMessageCell:(RCMessageModel *)model inView:(UIView *)view {
//    [super didLongTouchMessageCell:model inView:view];
}

- (void)didTapMessageCell:(RCMessageModel *)model {
    if ([model.objectName isEqualToString:@"RC:SightMsg"] || [model.objectName isEqualToString:@"RC:ImgMsg"]) {
        if (model.messageDirection == MessageDirection_RECEIVE && ![MBUserAccount defaultAccount].isVip) {
            [self.navigationController pushViewController:[KLVipViewController new] animated:YES];
            return;
        }
    }    
    //图片RC:ImgMsg 视频RC:SightMsg
//    if ([model.objectName isEqualToString:@"RC:SightMsg"]) {
//        MBChatPreviewVideoViewController *previewVc = [MBChatPreviewVideoViewController new];
//        RCSightMessage *sightMessage = (RCSightMessage *)model.content;
////        if (sightMessage.thumbnailImage == nil) {
//            previewVc.videoUrl = [NSURL URLWithString:sightMessage.sightUrl];
////        } else {
////            previewVc.videoUrl = [NSURL fileURLWithPath:sightMessage.localPath];
////        }
//        previewVc.modalPresentationStyle = UIModalPresentationFullScreen;
//        [self.navigationController presentViewController:previewVc animated:YES completion:nil];
//    } else {
        [super didTapMessageCell:model];
//    }
}

- (UIView *)getBgView{
    UITextField *bgTextField = [[UITextField alloc] init];
    [bgTextField setSecureTextEntry:true];
    
    UIView *bgView = bgTextField.subviews.firstObject;
    [bgView setUserInteractionEnabled:true];
    bgView.backgroundColor = UIColor.clearColor;
    return bgView;
}

- (void)dealloc {
    [IQKeyboardManager sharedManager].enable = YES;
}

#pragma mark - UI
- (void)setupUI {
    
    for (UIView *view in self.view.subviews) {
        CGRect frame = view.frame;
        [view removeFromSuperview];
        [self.secView addSubview:view];
        view.frame = frame;
    }
    
    [self.view addSubview:self.secView];
    [self.view sendSubviewToBack:self.secView];
    [self.secView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.backImageView];
    [self.view sendSubviewToBack:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
    [self.chatSessionInputBarControl setInputBarType:RCChatSessionInputBarControlDefaultType style:RC_CHAT_INPUT_BAR_STYLE_CONTAINER];
    self.chatSessionInputBarControl.inputContainerView.hideEmojiButton = YES;
    
    RCKitConfigCenter.ui.globalMessagePortraitSize = CGSizeMake(MBHeightScale(42), MBHeightScale(42));
    RCKitConfigCenter.ui.globalMessageAvatarStyle = RC_USER_AVATAR_CYCLE;
    //原sdk在最外层加了一层白色view,目的是为了保护底部安全区? 不得而知,暂时改颜色,如果没用后期可以移除.
    UIView *whiteView = self.secView.subviews[0];
    whiteView.backgroundColor = UIColor.clearColor;
//    [whiteView removeFromSuperview];
    
    //原sdk在chatSessionInputBarControl顶部有一条白线,不知何为,暂时改颜色,如果没用后期可以移除.
    CALayer *whiteLayer = self.chatSessionInputBarControl.layer.sublayers[1];
    whiteLayer.backgroundColor = UIColor.clearColor.CGColor;
    
    self.conversationMessageCollectionView.showsVerticalScrollIndicator = NO;
    self.conversationMessageCollectionView.backgroundColor = UIColor.clearColor;
    self.conversationMessageCollectionView.layer.cornerRadius = MBHeightScale(40);
    
    CGRect frame = self.conversationMessageCollectionView.frame;
    CGRect frame1;
    frame1 = CGRectMake(frame.origin.x, MBHeightScale(16)+StatusBarAndNavigationBarHeight, frame.size.width, 200);
    self.conversationMessageCollectionView.frame = frame1;


    
    self.chatSessionInputBarControl.backgroundColor = UIColor.clearColor;
    UIView *inputWhiteView = [UIView new];
    inputWhiteView.backgroundColor = UIColor.whiteColor;
    inputWhiteView.layer.cornerRadius = 20;
    [self.chatSessionInputBarControl addSubview:inputWhiteView];
    [self.chatSessionInputBarControl sendSubviewToBack:inputWhiteView];
    [inputWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MBWidthScale(12));
        make.right.mas_equalTo(MBWidthScale(-12));
        make.top.bottom.equalTo(self.chatSessionInputBarControl);
        if (TabbarSafeBottomMargin == 0) {
            make.bottom.mas_equalTo(MBHeightScale(-7));
        }
    }];
    
//    self.chatSessionInputBarControl.emojiButton
    self.chatSessionInputBarControl.inputTextView.backgroundColor = HEXS(@"ffffff");
    self.chatSessionInputBarControl.inputTextView.textColor = HEXS(@"333333");
    self.chatSessionInputBarControl.inputTextView.font = PDRegularScale(14);
    
    
//    [self.chatSessionInputBarControl.recordButton setImage:ImageWithName(@"chat_select_image") forState:0];
//    [self.chatSessionInputBarControl.recordButton addTarget:self action:@selector(imageSelectAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.chatSessionInputBarControl.emojiButton setImage:ImageWithName(@"chat_send_message") forState:0];
//    [self.chatSessionInputBarControl.emojiButton addTarget:self action:@selector(sendMessageAction) forControlEvents:UIControlEventTouchUpInside];
        
    
    [self.chatSessionInputBarControl.inputTextView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
//        make.bottom.mas_equalTo(MBHeightScale(-38));
        make.left.mas_equalTo(MBWidthScale(95));
        make.height.mas_equalTo(MBHeightScale(40));
    }];
    
    [self.view addSubview:self.conversitionNavView];
    [self.conversitionNavView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(StatusBarAndNavigationBarHeight);
    }];
    
    [self.chatSessionInputBarControl.inputContainerView addSubview:self.imageSelectBtn];
    [self.imageSelectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(MBWidthScale(32));
        make.centerY.equalTo(self.chatSessionInputBarControl.inputTextView);
        make.height.mas_equalTo(MBHeightScale(20));
        make.width.mas_equalTo(MBHeightScale(20));
    }];
    self.imageSelectBtn.layer.cornerRadius = MBHeightScale(20);
    
    [self.chatSessionInputBarControl.inputContainerView addSubview:self.sendMessageBtn];
    [self.sendMessageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(MBWidthScale(-30));
        make.centerY.equalTo(self.imageSelectBtn);
        make.height.mas_equalTo(MBHeightScale(20));
        make.width.mas_equalTo(MBHeightScale(20));
    }];
    
    [self.emojiSelectBtn removeFromSuperview];
    [self.chatSessionInputBarControl.inputContainerView addSubview:self.emojiSelectBtn];
    [self.emojiSelectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imageSelectBtn.mas_right).offset(MBWidthScale(15));
        make.centerY.equalTo(self.imageSelectBtn);
        make.height.mas_equalTo(MBHeightScale(20));
        make.width.mas_equalTo(MBHeightScale(20));
    }];
    
    self.chatSessionInputBarControl.inputTextView.toolbarPlaceholder = @"";
    [self.placeLab sizeToFit];
    [self.chatSessionInputBarControl.inputTextView addSubview:self.placeLab];
    [self.chatSessionInputBarControl.inputTextView setValue:self.placeLab forKey:@"_placeholderLabel"];
}

#pragma mark - Setter && Getter
- (MBConversitionNavView *)conversitionNavView {
    if (!_conversitionNavView) {
        _conversitionNavView = [MBConversitionNavView new];
        _conversitionNavView.userId = self.targetId;
//        __WeakSelf
        _conversitionNavView.conversitionBlock = ^{
//            MBConversationViewController *conversationVC = [[MBConversationViewController alloc] initWithConversationType:ConversationType_PRIVATE targetId:@""];
//            [weakSelf.navigationController pushViewController:conversationVC animated:YES];
        };
    }
    return _conversitionNavView;
}

- (UIButton *)imageSelectBtn {
    if (!_imageSelectBtn) {
        _imageSelectBtn = [[UIButton alloc] init];
        [_imageSelectBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_imageSelectBtn setImage:ImageWithName(@"chat_select_image") forState:0];
        [_imageSelectBtn addTarget:self action:@selector(imageSelectAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _imageSelectBtn;
}

- (UIButton *)emojiSelectBtn {
    if (!_emojiSelectBtn) {
        _emojiSelectBtn = self.chatSessionInputBarControl.emojiButton;
        [_emojiSelectBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        _emojiSelectBtn.hidden = NO;
        [_emojiSelectBtn setImage:ImageWithName(@"chat_select_emoji") forState:0];
    }
    return _emojiSelectBtn;
}

- (UIButton *)sendMessageBtn {
    if (!_sendMessageBtn) {
        _sendMessageBtn = [[UIButton alloc] init];
        [_sendMessageBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_sendMessageBtn setImage:ImageWithName(@"chat_send_message") forState:0];
        [_sendMessageBtn addTarget:self action:@selector(sendMessageAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendMessageBtn;
}

- (MBChatDataManager *)chatDataManager {
    if (!_chatDataManager) {
        _chatDataManager = [[MBChatDataManager alloc] init];
    }
    return _chatDataManager;
}

- (UIView *)secView {
    if (!_secView) {
        _secView = [self getBgView];
    }
    return _secView;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"home_back_image");
    }
    return _backImageView;
}

- (UILabel *)placeLab {
    if (!_placeLab) {
        _placeLab = [UILabel new];
        _placeLab.text = @"Your message...";
        _placeLab.textColor = HEXS(@"999999");
        _placeLab.font = PDRegularScale(14);
    }
    return _placeLab;
}
@end
